﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIProgressAmount : MonoBehaviour
{
    [Header("=====  图片设置 =====")]

    public Image imageBg;

    public Image imageBottom;

    public Image imageTop;

    [Header("=====  颜色设置 =====")]

    public Color colorBg;
    public Color colorHeal;
    public Color colorDanger;
    public Color colorReduce;
    public Color colorIncrease;

    [Header("=====  危险范围 =====")]

    public float dangerRange = 0.2f;

    [Header("=====  进度设置 =====")]

    [Range(0, 1)]
    public float progress = 0;

    private float _progress = 0;


    // Start is called before the first frame update

    private float _dangerFadeTime = 0;

    private void Start()
    {
        if (this.imageTop) this.imageTop.color = colorHeal;
        this._progress = progress;
        this.UpdateBarState();
    }

    // #if UNITY_EDITOR
    //     private void OnValidate()
    //     {
    //         this._progress = progress;
    //         if(this.imageTop)this.imageTop.color = colorHeal;
    //         this.UpdateBarState();
    //     }
    // #endif

    public void CheckLessHpFade()
    {
        bool lessHp = false;
        lessHp = progress <= dangerRange;

        if (lessHp)
        {
            this._dangerFadeTime += Time.deltaTime * 2.0f;
            float t = _dangerFadeTime % 1.0f;

            this.imageBg.color = Color.LerpUnclamped(this.colorBg, this.colorDanger, (t > 0.5f ? (1 - t) : t) * 2.0f);

        }
        else
        {
            //恢复正常底色
            this.imageBg.color = Color.LerpUnclamped(this.imageBg.color, this.colorBg, 10 * Time.deltaTime);
        }
    }

    public void UpdateBarState()
    {
        bool increase = this.progress >= this._progress;

        if (this.imageBottom)
        {
            this.imageBottom.fillAmount = increase ? this.progress : this._progress;
            this.imageBottom.color = increase ? this.colorIncrease : this.colorReduce;
        }

        if (this.imageTop)
        {
            this.imageTop.fillAmount = increase ? this._progress : this.progress;
        }

    }

    // Update is called once per frame
    void Update()
    {
        if (Mathf.Abs(this.progress - this._progress) < 0.01f)
        {
            this._progress = this.progress;
        }
        else
        {
            this._progress = Mathf.Lerp(this._progress, this.progress, Time.deltaTime * 2);
        }

        //更新血条状态
        this.UpdateBarState();
        //更新血条背景状态
        this.CheckLessHpFade();

    }
}
